<template>
  <u-mask :show="show" :duration="100" :zoom="false">
    <view v-if="show" class="promote-content">
      <!-- 单图广告 -->
      <view v-if="currentActive.content_type == ContentTypeEnum.SINGLE.value" class="ad-picture" @click="handleSingleItem()">
        <image class="image" :src="currentActive.content_config[ContentTypeEnum.SINGLE.value].imageUrl" mode="widthFix"></image>
      </view>
      <!-- 多图轮播 -->
      <view v-if="currentActive.content_type == ContentTypeEnum.SWIPER.value" class="ad-swiper">
        <u-swiper bg-color="unset" name="imageUrl" :list="currentActive.content_config[ContentTypeEnum.SWIPER.value].adList"
          :interval="3000" :effect3d="true" :height="640" @click="handleSwiperItem" />
      </view>
      <!-- 关闭按钮 -->
      <view class="action-close" @click="handleClose()">
        <u-icon name="close-circle" :effect3d="true" />
      </view>
      <!-- 自动关闭倒计时 -->
      <view v-if="currentActive.close_mode == CloseModeEnum.AUTO.value" class="close-countdown">
        <text>{{ times }}</text>
        <text>秒后自动关闭</text>
      </view>
    </view>
  </u-mask>
</template>

<script>
  import { getCurrentPage, onLink } from '@/core/app'
  import storage from '@/utils/storage'
  import * as Api from '@/api/promote'
  import { ContentTypeEnum, CloseModeEnum, FrequencyEnum } from '@/common/enum/market/promote'
  import { inArray } from '../../utils/util'

  const LocalIndex = 'PromoteViews'

  export default {
    props: {

    },
    data() {
      return {
        // 枚举类
        ContentTypeEnum,
        CloseModeEnum,
        FrequencyEnum,
        // 弹窗显示隐藏
        show: false,
        // 倒计时时长(秒)
        times: 0,
        // 定时器句柄
        interHandle: undefined,
        // 当前展现的活动索引
        current: 0,
        // 开屏推广活动列表
        activeList: []
      }
    },
    computed: {
      // 当前展现的活动详情
      currentActive() {
        return this.activeList.length ? this.activeList[this.current] : null
      }
    },
    created() {
      // 延迟执行, 否则$checkModule方法不生效
      setTimeout(() => {
        // 获取开屏推广活动
        this.$checkModule('market-promote') && this.getActiveList()
      }, 1000)
    },
    methods: {

      // 获取开屏推广活动
      async getActiveList() {
        const app = this
        // 开屏推广活动列表
        const result = await Api.activeList()
        // 整理允许展现的活动列表
        app.activeList = app.getUsableList(result.data.list)
        // 展现弹窗
        app.activeList.length > 0 && app.showPromote(0)
      },

      // 展现弹窗
      showPromote(index = 0) {
        const app = this
        app.show = true
        app.current = index
        // 弹窗关闭方式为自动关闭时启动定时器
        if (app.currentActive.close_mode == CloseModeEnum.AUTO.value) {
          app.startTimer(app.currentActive.seconds)
        }
        // 记录活动展现状态
        app.setViewsState()
      },

      // 整理允许展现的活动列表
      getUsableList(list) {
        const app = this
        const localData = storage.get(LocalIndex)
        const todayTime = new Date(new Date().toLocaleDateString()).getTime()
        return list.filter(item => {
          // 判断展现的页面
          const currentPage = getCurrentPage()
          if (!inArray(currentPage.path, item.pages)) {
            return false
          }
          // 查找本地展现记录
          const localItem = localData[item.promote_id]
          if (!localItem) {
            return true
          }
          // 只推荐一次
          if (item.frequency == FrequencyEnum.ONCE.value) {
            return false
          }
          // 每天推荐一次：判断当天0点的时间戳是否大于已展现的时间
          if (item.frequency == FrequencyEnum.EVERY_DAY.value && todayTime > localItem.showTime) {
            return true
          }
          return false
        })
      },

      // 手动关闭弹窗
      handleClose() {
        this.show = false
        this.endTimer()
        // 关闭后自动展现下一个广告 (此处定时1s)
        const next = this.current + 1
        if (this.activeList.length > next) {
          setTimeout(() => this.showPromote(next), 1000)
        }
      },

      // 执行定时器 (倒计时关闭弹窗)
      startTimer(times) {
        const app = this
        app.times = times
        app.interHandle = setInterval(() => {
          app.times--
          if (app.times <= 0) {
            app.handleClose()
          }
        }, 1000)
      },

      // 结束定时器
      endTimer() {
        this.times = 0
        clearInterval(this.interHandle)
      },

      // 记录活动展现状态
      setViewsState() {
        const { currentActive } = this
        // 将展现状态记录到本地缓存
        const data = storage.get(LocalIndex) || {}
        storage.set(LocalIndex, {
          ...data,
          [currentActive.promote_id]: {
            // promoteId: currentActive.promote_id,
            // frequency: currentActive.frequency,
            showTime: new Date().getTime(), // 展现的时间
          }
        })
        // 请求后端记录浏览次数
        this.updateViewsNum(currentActive.promote_id)
      },

      // 单图广告点击事件
      handleSingleItem() {
        const { currentActive } = this
        // 请求后端记录点击次数
        this.updateClickNum(currentActive.promote_id)
        // 链接点击事件
        onLink(currentActive.content_config[ContentTypeEnum.SINGLE.value].link)
        // 关闭当前广告
        this.handleClose()
      },

      // 轮播图点击事件
      handleSwiperItem(index) {
        const { currentActive } = this
        // 请求后端记录点击次数
        this.updateClickNum(currentActive.promote_id)
        // 链接点击事件
        onLink(currentActive.content_config[ContentTypeEnum.SWIPER.value].adList[index].link)
      },

      // 请求后端累积浏览次数
      updateViewsNum(promoteId) {
        Api.updateViewsNum(promoteId)
      },

      // 请求后端累积点击次数
      updateClickNum(promoteId) {
        Api.updateClickNum(promoteId)
      },

    }
  }
</script>

<style lang="scss" scoped>
  .promote-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .action-close {
    margin-top: 40rpx;
    color: #b9b9b9;
    font-size: 42rpx;
  }

  .close-countdown {
    margin-top: 30rpx;
    color: #b9b9b9;
    font-size: 24rpx;
  }

  .ad-picture {

    .image {
      display: block;
      width: 540rpx;
    }
  }

  .ad-swiper {
    width: 580rpx;
  }
</style>